package com.example.myproject.service;

import com.example.myproject.model.ChatMessage;
import com.example.myproject.model.ChatMessageEntity;
import com.example.myproject.repository.ChatMessageRepository;
import org.springframework.messaging.simp.user.SimpUserRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.util.List;
import java.util.Comparator;
import java.util.stream.Collectors;
import java.util.Optional;

@Service
public class ChatService {

    @Autowired
    private ChatMessageRepository chatMessageRepository;

    @Autowired
    private SimpUserRegistry simpUserRegistry;

    @Transactional
    public ChatMessageEntity saveMessage(ChatMessage chatMessage) {
        ChatMessageEntity messageEntity = new ChatMessageEntity();
        messageEntity.setFromUser(chatMessage.getFrom());
        messageEntity.setToUser(chatMessage.getTo());
        messageEntity.setContent(chatMessage.getContent());
        messageEntity.setTimestamp(chatMessage.getTimestamp());
        messageEntity.setType(ChatMessageEntity.MessageType.valueOf(chatMessage.getType().name()));

        // 判断接收方是否在线
        boolean recipientOnline = simpUserRegistry.getUsers()
                .stream()
                .anyMatch(user -> user.getName().equals(chatMessage.getTo()));

        // 如果接收方在线，则消息直接标记为已读，否则为未读
        if (recipientOnline) {
            messageEntity.setReadStatus(ChatMessageEntity.ReadStatus.READ);
        } else {
            messageEntity.setReadStatus(ChatMessageEntity.ReadStatus.UNREAD);
        }

        return chatMessageRepository.save(messageEntity);
    }

    /**
     * 标记由 senderUsername 发送给 readerUsername 的未读消息为已读，
     * 并返回这些更新后的消息的 DTO 列表。
     * @param readerUsername 当前读取消息的用户 (即消息的接收方)
     * @param senderUsername 消息的原始发送方
     * @return 被标记为已读的 ChatMessage DTO 列表
     */
    @Transactional
    public List<ChatMessage> markMessagesAsReadAndRetrieveForSender(String readerUsername, String senderUsername) {
        // 找出由 senderUsername 发送给 readerUsername 且未读的消息
        List<ChatMessageEntity> messagesToMark = chatMessageRepository.findByFromUserAndToUserAndReadStatus(
                senderUsername, readerUsername, ChatMessageEntity.ReadStatus.UNREAD);

        for (ChatMessageEntity msg : messagesToMark) {
            msg.setReadStatus(ChatMessageEntity.ReadStatus.READ);
            chatMessageRepository.save(msg); // 保存更新
        }

        // 转换并返回这些刚刚被标记为已读的消息（DTOs）
        return messagesToMark.stream()
                .map(this::convertToDto)
                .collect(Collectors.toList());
    }


    public List<ChatMessage> getConversationHistory(String user1, String user2) {
        List<ChatMessageEntity> messages = chatMessageRepository.findConversation(user1, user2, user1, user2);

        // 确保返回最新的20条消息
        return messages.stream()
                .sorted(Comparator.comparing(ChatMessageEntity::getTimestamp)) // 按时间排序
                .skip(Math.max(0, messages.size() - 20)) // 跳过旧消息，只取最新的20条
                .map(this::convertToDto)
                .collect(Collectors.toList());
    }

    public Optional<ChatMessageEntity> getLatestMessage(String fromUser, String toUser, Instant timestamp) {
        return chatMessageRepository.findByFromUserAndToUserAndTimestamp(fromUser, toUser, timestamp);
    }

    private ChatMessage convertToDto(ChatMessageEntity entity) {
        ChatMessage dto = new ChatMessage();
        dto.setId(entity.getId());
        dto.setFrom(entity.getFromUser());
        dto.setTo(entity.getToUser());
        dto.setContent(entity.getContent());
        dto.setTimestamp(entity.getTimestamp());
        dto.setType(ChatMessage.MessageType.valueOf(entity.getType().name()));
        dto.setReadStatus(entity.getReadStatus().name());
        return dto;
    }
}